/*
  消息通知
   */
function msgNotify(msg, type, delay) {
  lightyear.loading(true)
  lightyear.notify(msg, type, delay, 'mdi mdi-emoticon-happy', 'top', 'center')
}

/*
check_item
 */
function check_item() {
  $(document).on("click", ".check-item", function () {
    let flag = $(".check-item:checked").length === $(".check-item").length;
    $("#check-all").prop("checked", flag);
  })
}

/*
批量删除
 */
function deleteBatch(url) {
  $("#deleteBatch").click(function () {
    let checkedItems = $(".check-item:checked")
    if (checkedItems.length === 0) {
      msgNotify("请先选择要删除的内容", "warning", 1500)
      return false
    }
    let del_idStr = "";
    $.each(checkedItems, function () {
      //组装规则id字符串
      del_idStr += $(this).parents("tr").find("td:eq(1)").text() + "-"
    })
    //去除删除的id多余的-
    del_idStr = del_idStr.substring(0, del_idStr.length - 1)
    $.confirm({
      title: '提示',
      content: '确认删除这些内容吗？',
      type: 'orange',
      typeAnimated: true,
      buttons: {
        confirm: {
          text: '确认',
          btnClass: 'btn-primary',
          action: function () {
            //发送ajax请求删除
            $.ajax({
              url: url + "/" + del_idStr,
              type: "DELETE",
              success: function (res) {
                //回到当前页面
                to_page(currentPage);
                msgNotify(res.msg, "success", "1500")
              }
            })
          }
        },
        cancel: {
          text: '取消',
          action: function () {
          }
        }
      }
    })
  })
}

/*
删除一个
 */
function deleteOne(url) {
  $(document).on("click", ".del_btn", function () {
    let del_btn = $(this)
    $.confirm({
      title: '提示',
      content: '确认删除吗',
      type: 'orange',
      typeAnimated: true,
      buttons: {
        confirm: {
          text: '确认',
          btnClass: 'btn-primary',
          action: function () {
            let id = del_btn.parents("tr").find("td:eq(1)").text()
            $.ajax({
              url: url + "/" + id,
              type: "delete",
              success: function (res) {
                to_page(currentPage)
                if (res.flag) {
                  msgNotify(res.msg, 'success', 1500)
                } else {
                  msgNotify(res.msg, 'danger', 1500)
                }
              }
            })
          }
        },
        cancel: {
          text: '取消',
          action: function () {
          }
        }
      }
    })
  })
}

//显示校验结果的提示信息
function show_validate_msg(item, status, msg) {
  $(item).parent().removeClass("has-success has-error")
  $(item).next("span").text("")
  if ("success" === status) {
    $(item).parent().addClass("has-success")
  } else if ("error" === status) {
    $(item).parent().addClass("has-error")
    $(item).parent().next("span").text(msg)
  }
}

//清空表单样式及内容
function reset_form(ele) {
  $(ele)[0].reset();
  //清空表单样式
  $(ele).find("*").removeClass("has-error has-success").removeAttr("disabled");
  $("#submit_btn").removeClass("hidden edit_submit")
  $("#edit_btn").addClass("hidden")
  $(ele).find(".help-block").text("");
}

/*
  解析分页导航条
   */
function parsePageNav(startPage, endPage, res, ul) {
  for (let i = startPage; i <= endPage; i++) {
    let numLi = $("<li></li>").append($("<a></a>").html(i))
    if (res.data.current === i) {
      numLi.addClass("active");
    }
    numLi.click(function () {
      to_page(i)
    })
    ul.append(numLi)
  }
}

/*
  解析显示分页条数据
   */
function build_page_nav(res) {
  //page_nav_area
  $("#page_nav_area").empty()
  let ul = $("<ul></ul>").addClass("pagination")

  //构建元素
  let firstPageLi = $("<li></li>").append($("<a></a>").append("首页").attr("href", "#"))
  let prePageLi = $("<li></li>").append($("<a></a>").append("&laquo;"))
  if (!(res.data.current > 1)) {
    firstPageLi.addClass("disabled")
    prePageLi.addClass("disabled")
  } else {
    //为元素添加点击翻页的事件
    firstPageLi.click(function () {
      to_page(1)
    })
    prePageLi.click(function () {
      to_page(res.data.current - 1)
    })
  }

  let nextPageLi = $("<li></li>").append($("<a></a>").append("&raquo;"))
  let lastPageLi = $("<li></li>").append($("<a></a>").append("末页").attr("href", "#"))
  if (res.data.current >= res.data.pages) {
    nextPageLi.addClass("disabled")
    lastPageLi.addClass("disabled")
  } else {
    nextPageLi.click(function () {
      to_page(res.data.current + 1)
    })
    lastPageLi.click(function () {
      to_page(res.data.pages)
    })
  }

  //添加首页和前一页 的提示
  ul.append(firstPageLi).append(prePageLi)

  // 遍历给ul添加页码提示
  if (res.data.pages > 5) {
    if (res.data.current > 3 || (res.data.current < (res.data.pages - 2))) {
      parsePageNav(res.data.current - 2, res.data.current + 2, res, ul)
    } else if (res.data.current < 3) {
      parsePageNav(1, 5, res, ul)
    } else {
      parsePageNav(res.data.pages - 4, res.data.pages, res, ul)
    }
  } else {
    parsePageNav(1, res.data.pages, res, ul)
  }

  //添加下一页和末页 的提示
  ul.append(nextPageLi).append(lastPageLi)

  //把ul加入到nav
  let navEle = $("<nav></nav>").append(ul)
  navEle.appendTo("#page_nav_area")
}

/*
  解析并显示分页信息
   */
function build_page_info(res) {
  $("#page_info_area").empty()
  $("#page_info_area").html("总计 <strong>" + res.data.total + "</strong> 条数据，当前是第\n" +
      "<input id=\"pn\" type=\"text\" style=\"width: 40px; height: 25px;\" value=\"" + res.data.current + "\">\n" +
      "页 / 总 <strong>" + res.data.pages + "</strong> 页")
  currentPage = res.data.current
}

/*
输入页码翻页
 */
function turnPage() {
  $(document).on("keydown", "#pn", function (event) {
    if (event.keyCode === 13 || event.keyCode === 108) {
      //正则校验页码输入框中的值
      if (/^\d+$/.test($("#pn").val())) {
        to_page($("#pn").val())
      } else {
        $("#pn").val("")
        msgNotify("请输入正确的页码", "danger", 1500)
      }
    }
  })
}

/*
详情模态框状态
 */
function detailModal(ele) {
  $(".modal-title").text("内容详情")
  //隐藏提交按钮
  $("#submit_btn").addClass("hidden")

  //让所有内容不可编辑
  $(ele).find("form select").attr("disabled", "disabled")
  $(ele).find("form input").attr("disabled", "disabled")
  //显示编辑按钮
  $("#edit_btn").removeClass("hidden")
}

/*
编辑模态框状态
 */
function editModal(ele) {
  $(".modal-title").text("更新内容")
  //隐藏编辑按钮
  $("#edit_btn").addClass("hidden")
  //显示提交按钮
  $("#submit_btn").removeClass("hidden")
  //让所有内容可编辑
  $(ele).find("form").find("*").removeAttr("disabled")
}

/*
格式化时间对象
 */
function formatTimeObj(datetime) {
  let year = datetime.year
  let month = datetime.monthValue.toString().padStart(2, '0')
  let day = datetime.dayOfMonth.toString().padStart(2, '0')
  let hour = datetime.hour.toString().padStart(2, '0')
  let minute = datetime.minute.toString().padStart(2, '0')
  let second = datetime.second.toString().padStart(2, '0')
  return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second
}

//格式化时间字符串
function formatTimeStr(value, row, index) {
  return value.replace('T', ' ')
}

/*
  bootstrap table重新加载数据
   */
function load(pn) {
  let $table = $("#table")
  if (pn !== undefined) {
    $table.bootstrapTable('refreshOptions', {pageNumber: 1})
  } else {
    //获取当前页
    let current = $table.bootstrapTable("getOptions").pageNumber
    $table.bootstrapTable('refreshOptions', {pageNumber: current});
  }
  $table.bootstrapTable('refresh');
}

/*
bootstrap table使用的批量删除
 */
function tb_deleteBatch(url) {
  $("#btn_delete").click(function () {
    let selRows = $("#table").bootstrapTable("getSelections");
    if (selRows.length === 0) {
      msgNotify("请先选择要删除的内容", "warning", 1500)
      return
    }
    let idStr = ''
    $.each(selRows, function (i) {
      //组装规则id字符串
      idStr += this.id + "-"
    })
    //去除删除的id多余的-
    idStr = idStr.substring(0, idStr.length - 1)
    $.confirm({
      title: '提示',
      content: '确认删除这些内容吗？',
      type: 'orange',
      typeAnimated: true,
      buttons: {
        confirm: {
          text: '确认',
          btnClass: 'btn-primary',
          action: function () {
            //发送ajax请求删除
            $.ajax({
              url:  url + "/" + idStr,
              type: "DELETE",
              success: function (res) {
                //回到当前页面
                load()
                if (res.flag) {
                  msgNotify(res.msg, "success", "1500")
                } else {
                  msgNotify(res.msg, "danger", "1500")
                }
              },
              error() {
                msgNotify("删除失败，请稍后再试", "danger", "1500")
              }
            })
          }
        },
        cancel: {
          text: '取消',
          action: function () {
          }
        }
      }
    })
  })
}

/*
bootstrap table的单个删除
 */
function tb_deleteOne(id, url) {
  $.confirm({
    title: '提示',
    content: '确认删除吗',
    type: 'orange',
    typeAnimated: true,
    buttons: {
      confirm: {
        text: '确认',
        btnClass: 'btn-primary',
        action: function () {
          $.ajax({
            url: url + "/" + id,
            type: "delete",
            success: function (res) {
              load()
              if (res.flag) {
                msgNotify(res.msg, 'success', 1500)
              } else {
                msgNotify(res.msg, 'danger', 1500)
              }
            }
          })
        }
      },
      cancel: {
        text: '取消',
        action: function () {
        }
      }
    }
  })
}

/*
批量改变状态
 */
function changeStatusBatch(status, url) {
  let selRows = $("#table").bootstrapTable("getSelections");
  if (selRows.length === 0) {
    msgNotify("请先选择要更改的内容", "warning", 1500)
    return
  }
  let list = []
  $.each(selRows, function () {
    let temp = {
      id: this.id,
      status: status
    }
    list.push(temp)
  })
  let listJSON = JSON.stringify(list)
  $.ajax({
    url: url,
    type: "PUT",
    data: listJSON,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    traditional: true,
    success: function (data) {
      load()
      if (data.flag) {
        msgNotify(data.msg, "success", 1500)
      } else {
        msgNotify(data.msg, "danger", 1500)
      }
    },
    error: function () {
      msgNotify("修改失败，请稍后再试", "warning", 1500)
    }
  })
}

/*
  添加标签页
   */
function addTab(title, url) {   //title 选项卡的名字 //url 选项卡的链接地址
  parent.$(parent.document).data('multitabs').create({
    iframe: true,              //指定为iframe模式，当值为false的时候，为智能模式，自动判断（内网用ajax，外网用iframe）。缺省为false。
    title: title,                //标题（可选），没有则显示网址
    url: url                    //链接（必须），如为外链，强制为info页
  }, true);
}

// 查看订单详情
function showOrder(id, carTypeId, price, distance, status) {
  $.get('/orders/'+id, {status: status}, function (res) {
    if (res.flag) {
      let order = res.data
      $("#orderId").html(order.id)
      $("#customerName").html(order.customer.name)
      $("#customerPhone").html(order.customer.phone)
      $("#carTypeName").html(order.carType.name)
      $("#licence").html(order.car.licence)
      $("#createTime").html(formatTimeObj(order.createTime))
      $("#appointmentTime").html(formatTimeObj(order.appointmentTime))
      $("#startPoint").html(order.startPoint)
      $("#endPoint").html(order.endPoint)
      $("#distance").html(order.distance + ' 公里')
      $("#price").html(order.price + ' 元')
      $("#remark").html(order.remark)
      fillOtherOrderInfo(order)
    }
  })

  $.get("/wx/rule", {typeId: carTypeId}, function (res) {
    if (res.flag) {
      let ruleVo = res.data
      $("#startPrice strong:eq(0)").text(ruleVo.startPrice)
      $("#priceBetween5And25 strong:eq(0)").text(ruleVo.priceBetween5And25)
      $("#priceBetween25And60 strong:eq(0)").text(ruleVo.priceBetween25And60)
      $("#priceGt60 strong:eq(0)").text(ruleVo.priceGt60)
      $("#total_price").text(price)

      $("#startPrice strong:eq(1)").text(ruleVo.startPrice)
      if (5 <= distance && distance <= 25) {
        $("#priceBetween5And25 strong:eq(1)").text((distance - 5) * ruleVo.priceBetween5And25)
      } else if (distance <= 60) {
        $("#priceBetween5And25 strong:eq(1)").text(20 * ruleVo.priceBetween5And25)
        $("#priceBetween25And60 strong:eq(1)").text((distance - 25) * ruleVo.priceBetween25And60)
      } else if (distance > 60) {
        $("#priceBetween5And25 strong:eq(1)").text(20 * ruleVo.priceBetween5And25)
        $("#priceBetween25And60 strong:eq(1)").text(35 * ruleVo.priceBetween25And60)
        $("#priceGt60 strong:eq(1)").text((distance - 60) * ruleVo.priceGt60)
      }
    }
  })

  $("#orderInfoModal").modal({
    backdrop: "static"
  })
}

/*
填充其他订单信息
 */
function fillOtherOrderInfo(res) {
}

// 操作按钮
function btnGroup() {
  let html =
      '<a href="#!" class="btn btn-xs btn-default m-r-5 edit-btn" title="编辑" data-toggle="tooltip"><i class="mdi mdi-pencil"></i></a>' +
      '<a href="#!" class="btn btn-xs btn-default m-r-5 show-btn" title="查看" data-toggle="tooltip"><i class="mdi mdi-eye"></i></a>' +
      '<a href="#!" class="btn btn-xs btn-default del-btn" title="删除" data-toggle="tooltip"><i class="mdi mdi-window-close"></i></a>';
  return html;
}

//jquery获得path路径
function getContextPath() {
  let pathName = document.location.pathname;
  let index = pathName.substr(1).indexOf("/");
  let result = pathName.substr(0, index + 1);
  return result;
}

//超链接的格式化器
function aFormatter(value, row, index) {
  return [
    '<a href="#">' + value + '</a>'
  ].join("")
}